#include <Windows.h>
#include <tchar.h>
#include "resource.h"

#define WM_CLEAR	WM_APP + 1000

int CALLBACK DlgProc(HWND hDlg, UINT nMsg, WPARAM wParam, LPARAM lParam)
{
	static HICON* pLarge;
	static HICON* pSmall;
	static UINT nCount;
	switch (nMsg)
	{
		case WM_INITDIALOG:
		{
			SetWindowText(hDlg, _T("Demo0070"));

			UINT nWidth		= GetSystemMetrics(SM_CXSCREEN);
			UINT nHeight	= GetSystemMetrics(SM_CYSCREEN);
			RECT rtClient;
			GetClientRect(hDlg, &rtClient);
			SetWindowPos(hDlg, NULL, (nWidth - (rtClient.right - rtClient.left)) / 2, (nHeight - (rtClient.bottom - rtClient.top)) / 2, 0, 0, SWP_NOSIZE);
			
			break;
		}
		case WM_CLEAR:
		{
			if (0 < nCount)
			{
				for (int ii = 0; ii < nCount; ii++)
				{
					DestroyWindow(GetDlgItem(hDlg, 1000 + ii));
					DestroyIcon(pLarge[ii]);
				}
				LocalFree(pLarge);
				InvalidateRect(hDlg, NULL, TRUE);
			}
			break;
		}
		case WM_COMMAND:
		{
			switch (LOWORD(wParam))
			{
				case IDC_BTNBROWSE:
				{
					TCHAR szFilePath[MAX_PATH]	= {0};
					OPENFILENAME ofn			={0};
					ofn.lStructSize				= sizeof(ofn);
					ofn.hwndOwner				= hDlg;
					ofn.lpstrFile				= szFilePath;
					ofn.nMaxFile				= MAX_PATH;
					ofn.Flags					= OFN_EXPLORER;
					ofn.lpstrFilter				= _T("Execute file(*.exe)\0*.exe\0DLL FILE (*.dll)\0*.dll\0\0");
					if (GetOpenFileName(&ofn))
					{
						SendMessage(hDlg, WM_CLEAR, 0, 0);

						SetWindowText(GetDlgItem(hDlg, IDC_STCFILEPATH), szFilePath);
						
						UINT nCount = ExtractIconEx(szFilePath, -1, NULL, NULL, 0);
						pLarge = (HICON*)LocalAlloc(LPTR, sizeof(HICON) * nCount);
						HICON* pSmall = (HICON*)LocalAlloc(LPTR, sizeof(HICON) * nCount);
						ExtractIconEx(szFilePath, 0, pLarge, NULL, nCount);
									
						RECT rtClient;
						GetClientRect(GetDlgItem(hDlg, IDC_STCFILEPATH), &rtClient);
						int x = rtClient.left + 10;
						int y = rtClient.bottom + 50;
						int nWidth	= 32;
						int nHeight = 32;
						for (int ii = 0; ii < nCount; ii++)
						{
							UINT nID = 2000 + ii;
							CreateWindow(_T("static"), _T(""), WS_CHILD|WS_VISIBLE|SS_ICON, x, y, nWidth, nHeight, hDlg, (HMENU)nID, NULL,  NULL);
							x += nWidth + 5;

							int nTmp = 0;
							if (NULL != (HICON)*pLarge)
							{
								SendDlgItemMessage(hDlg, nID, STM_SETICON, (WPARAM)pLarge[ii], 0);
							} 
																					
							if ((ii != 0) && 0 == (ii % 30))
							{
								x = rtClient.left + 10;
								y += nHeight + 10;
							}							
						}
					}
					break;
				}
			}
			break;
		}
		case WM_CLOSE:
		{
			SendMessage(hDlg, WM_CLEAR, 0, 0);

			PostQuitMessage(0);
			break;
		}
	}

	return 0;
}

BOOL WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE hPreInstance, LPTSTR szCmdLine, int nShowCmd)
{
	DialogBox(hInstance, MAKEINTRESOURCE(IDD_DIALOG), NULL, DlgProc);

	return TRUE;
}